from calm.sensor import Sensor
from ai.bin import decode
from system.vec2 import Vec2

import math

class DirectionSensor(Sensor):
    def __init__(self, controller, vars, numSlices = 8):
        Sensor.__init__(self, controller, vars, numSlices)
        
        self.numSlices = numSlices
        self.point = (0,0)
        
    def acceptBits(self, bits):
        bitSlice = decode.decodeIntRange(bits,0,len(bits),0,self.numSlices+1)
        
        agentPos = Vec2(self.agent.getVar("pos"))
        sensorPos = Vec2(self.point)
        rot = self.agent.getVar("rot")
        th = rot - (sensorPos - agentPos).angle()
        while th < 0:
            th += math.pi * 2
        while th > math.pi * 2:
            th -= math.pi * 2
        thStep = math.pi * 2 / float(self.numSlices)
        thSlice = int(th / thStep)
        
        #if '_' not in self.controller.getVar("path"):
            #print bitSlice, thSlice#, th, sensorPos, agentPos
        
        return bitSlice == thSlice
